<template>
    <div>
        <el-dialog
            title="修改分类"
            :visible.sync="dialogVisible"
            width="880px">
            <el-form ref="form" :model="form" label-width="120px" size="small">
                <el-form-item label="分类名称:" prop="name"
                              :rules="[{required: true, message: '请输入分类名称', trigger: 'blur'}]">
                    <el-input v-model="form.name" placeholder="请输入分类名称"></el-input>
                </el-form-item>
                <el-form-item label="层级:" prop="level" :rules="rules.level">
                    <el-input v-model="form.level" placeholder="请输入层级"></el-input>
                </el-form-item>
                <el-form-item label="是否显示:" prop="name">
                    <el-switch
                        v-model="form.isShow"
                        active-color="#8cc5ff"
                        active-value="1"
                        inactive-value="0"
                        inactive-color="#eaecf0">
                    </el-switch>
                </el-form-item>
                <el-form-item label="农场图片:" prop="image">
                    <el-upload
                        class="avatar-uploader"
                        :action="action"
                        :show-file-list="false"
                        :headers="{ Authorization: 'Bearer ' + token }"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" style="width: 100%; height: 100%;">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="关键字:" prop="keyword">
                    <el-input v-model="form.keyword" placeholder="请输入关键字"></el-input>
                </el-form-item>
                <el-form-item label="描述:" prop="description">
                    <el-input v-model="form.description" type="textarea" rows="4" placeholder="请输入描述"></el-input>
                </el-form-item>
                <el-form-item label="排序:" prop="listOrder" :rules="rules.listOrder">
                    <el-input v-model="form.listOrder" placeholder="请输入排序"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel" size="small">取 消</el-button>
                <el-button type="primary" @click="onSubmit" size="small">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {mapState} from "vuex";
import {upDateCategory} from "@/index/api/shops/shopsManage"

export default {
    data() {
        return {
            dialogVisible: false,
            form: {
                parentId: 0,
                name: null,
                level: "",
                isShow: "",
                image: "",
                keyword: "",
                description: "",
                listOrder: "",
            },
            imageUrl: '',
            rules: {
                level: [
                    {
                        validator: this.validateLevel,
                        message: '请输入 1 到 127 之间的数字',
                        trigger: 'blur'
                    }
                ],
                listOrder: [
                    {
                        validator: this.validateNumber,
                        message: '请输入数字',
                        trigger: 'blur'
                    }
                ]
            }
        }
    },
    computed: {
        ...mapState(["token", "action", "baseUrl"]),
    },
    methods: {
        validateNumber(rule, value, callback) {
            if (value === '') {
                // 如果输入为空，不进行验证，不显示错误提示
                callback();
            } else if (!/^\d+$/.test(value)) {
                callback(new Error('请输入数字'));
            } else {
                callback();
            }
        },
        validateLevel(rule, value, callback) {
            if (value === '') {
                // 如果输入为空，不进行验证，不显示错误提示
                callback();
            } else if (!/^(?:1?[0-1]?[0-9]|12[0-7])$/.test(value)) {
                callback(new Error('请输入 1 到 127 之间的数字'));
            } else {
                callback();
            }
        },
        cancel() {
            this.dialogVisible = false;
        },
        showDialog(e, row) {
            this.form = row;
            row.isShow == 1 ? this.form.isShow = true : this.form.isShow = false
            this.imageUrl = this.baseUrl + row.image
            this.dialogVisible = !this.dialogVisible
        },
        onSubmit() {
            this.form.isShow = this.form.isShow ? 1 : 0
            this.$refs["form"].validate((valid) => {
                if (valid) {
                    upDateCategory(this.form, this.form.id).then(res => {
                        if (res.code == 200) {
                            this.dialogVisible = false;
                            this.$message({
                                message: res.message,
                                type: "success",
                            });
                            this.$parent.getRegionList();
                        } else {
                            this.$message({
                                message: res.message,
                                type: "error",
                            });
                        }
                    })
                } else {
                    this.$message.warning('请输入正确的信息')
                    return false;
                }
            });


        },
        handleAvatarSuccess(res, file) {
            this.imageUrl = URL.createObjectURL(file.raw);
            this.$message.success('上传成功')
            this.form.image = res.data.filePath
        },
        beforeAvatarUpload(file) {
            const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
            const isAllowedType = allowedTypes.includes(file.type);
            const isLt2M = file.size / 1024 / 1024 < 2;

            if (!isAllowedType) {
                this.$message.error('上传头像图片只能是 JPG、PNG 或 PDF 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传头像图片大小不能超过 2MB!');
            }

            return isAllowedType && isLt2M;
        },

    }
}
</script>

<style lang="less" scoped>

.flex-container {
    display: flex;
    align-items: center; /* 垂直居中 */
    margin-top: 10px;
}

/deep/ .el-upload {
    width: 313px;
    height: 268px;
    border: 1px #e0e0e0 dashed;

    .el-icon-plus {
        line-height: 268px;
    }
}
</style>
